use std::{
    fs::{self, DirEntry},
    path::Path, process::Command,
};

/// 根据给定的URL获取到HOST和BaseURL
pub fn parse_m3u8_url_get_host_and_baseurl(m3u8_url: &str) -> Result<(String, String), String> {
    let Ok(url_parser) = url::Url::parse(m3u8_url) else { return Result::Err("解析URL异常,URU不合法".to_string()); };

    let Some(host) = url_parser.host_str() else { return Result::Err("URL中无HOST信息".to_string()); };

    // 获取HOST信息
    let schema = url_parser.scheme();

    let host = schema.to_string() + "://" + host;

    // 路径分片
    let Some(path_segments) = url_parser.path_segments() else { return Err("URL中路径信息异常".to_string()) };
    let path_segments = path_segments.collect::<Vec<_>>();

    // 获取BaseURL
    let _segments = &path_segments[0..(path_segments.len() - 1)];
    let base_url = host.clone() + "/" + &_segments.join("/") + "/";

    Ok((host, base_url))
}

/// 生成list文件
pub fn generate_list_file(ts_dir: &Path) -> String {
    let dir = fs::read_dir(ts_dir).unwrap();
    let dir_list = dir.collect::<Vec<Result<DirEntry, _>>>();

    let mut dir_list = dir_list
        .iter()
        .filter(|it| {
            let Ok(entry) = it else { return false };

            let Ok(_type) =  entry.file_type() else { return false };

            if !_type.is_file() {
                return false;
            }

            let _name = entry.file_name().clone();

            let Some(name) = _name.to_str() else { return false };

            name.ends_with(".ts")
        })
        .map(|it| {
            let Ok(entry) = it else { return None};
            let _name = entry.file_name().clone();
            let Some(name) = _name.to_str() else { return None };
            let name = name.replace(".ts", "");
            return Some(name);
        })
        .filter(|it| it.is_some())
        .map(|it| it.unwrap().parse::<u32>())
        .filter(|it| it.is_ok())
        .map(|it| it.unwrap())
        .collect::<Vec<_>>();

    dir_list.sort();

    let dir_list = dir_list
        .iter()
        .map(|it| format!("file '{}.ts'", it))
        .collect::<Vec<String>>();

    let contents = dir_list.join("\n");

    let file_list_file = ts_dir.join("file_list.txt");

    let _path = file_list_file.clone();
    // let path = _path.as_path();

    fs::write(file_list_file, contents).unwrap();

    _path.into_os_string().into_string().unwrap()
}

/// 合并视频
pub fn merge_video(list_path: &str, video_path: &str) -> std::process::ExitStatus {
    println!("{}转换视频至{}", list_path, video_path);
    let status = Command::new("ffmpeg")
        .args([
            "-f",
            "concat",
            "-safe",
            "0",
            "-i",
            &list_path,
            "-c",
            "copy",
            &video_path,
        ])
        .status()
        .unwrap();
    status
}
